<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
use App\Models\Article;

class FetchHtmlUrl extends Command
{

    const ARTICLE_URL_PREFIX = 'http://www.zoores.ac.cn/EN/abstract/abstract%u.shtml';

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:html_url {id?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'old version html url';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $client = new Client();
        $guzzleClient = new GuzzleClient(array(
            'timeout' => 60,
        ));
        $client->setClient($guzzleClient);
        $this->client = $client;

        $id = $this->argument('id');

        if ($id) {
            $this->processArticle(Article::find($id));
        } else {
            $page = 1;
            $count = 0;
            while (true) {
                $articles = Article::simplePaginate(5, ['*'], 'page', $page);
                $break = (bool)(count($articles->items()) == 0);
                foreach ($articles as $article) {
                    $this->processArticle($article);
                    $count++;
                }

                if ($break) break;
                $page++;
                $this->info($count++ . 'th articles html url fetched.');
            }
        }
    }

    public function processArticle($article)
    {
        $articleUrl = sprintf(self::ARTICLE_URL_PREFIX, $article->zr_id);
        // print_r($articleUrl);exit;
        try {
            $crawler = $this->client->request('GET', $articleUrl);
            if ($crawler->selectLink('RICH HTML')->count()) {
                $link = $crawler->selectLink('RICH HTML')->link();
                $article->html = str_replace('http://www.zoores.ac.cn', '', $link->getUri());
                $article->save();

                $this->info('insert html url' . $article->html);
            }
            $this->info("SKIP "  . $article->zr_id);
        } catch(\Exception $e) {

            $this->error($e->getMessage());
        }
    }
}
